<?php
defined( 'IN_DICE' ) or die( 'Access Error!' );

class ModelServer extends base {
    
  function __construct() {
    parent::__construct();
  }
  
  /**
   * 根据svid获得某个server的信息
   * @param $svid 服务器ID
   * @return array
   */
  public function get( $svid ) {
    if( !$svid = uint( $svid ) ) {
      return array();
    }
    $sql = "SELECT * FROM $this->server WHERE svid='$svid' LIMIT 1";
    return model::db()->get_one( $sql );
  }

  /**
   * 根据server类型返回一条server信息
   * @param int $type
   * @return array
   */
  public function getbytype( $type ) {
    $type = uint($type);
    if( !$type || !in_array($type, array(0, 1, 2, 3) ) ) {
      return array();
    }
    $sql = "SELECT * FROM $this->server WHERE svtype='$type' LIMIT 1";
    return model::db()->get_one( $sql );
  }
  
  /**
   * 获得所有的server
   *
   * @return array
   */
  public function getall() {
    $sql = "SELECT * FROM $this->server ";
    $record = model::db()->get_all($sql);
    return $record;
  }
  
  /**
   * 插入一条server表记录
   *
   * @param array $aS server的相关信息
   * @return int
   */
  public function insert( $aS ) {
    if( empty( $aS ) || count( $aS ) < 4 || !$aS['svip'] || !$aS['svport'] ) {
      return 0;
    }
    
    foreach ( $aS as $k => $v ) {
      $aS[$k] = model::db()->escape( $v );
    }
    $sql = "INSERT INTO $this->server SET svip='{$aS['svip']}',
            svport='{$aS['svport']}',status='{$aS['status']}',
            maxonline='{$aS['maxonline']}',online=0,svtype='{$aS['svtype']}' ";
    model::db()->exe( $sql );
    $id = model::db()->insertid();
    
    return (int)$id;
  }
  
  /**
   * 删除一个server
   *
   * @param int $svid
   * @return int
   */
  public function del( $svid ) {
    if( !$svid = uint( $svid ) ) {
      return 0;
    }
    
    $sql = "DELETE FROM $this->server WHERE svid='$svid' LIMIT 1";
    model::db()->exe( $sql );
    $flag = model::db()->update_rows();
    
    return (int)$flag;
  }
  
  /**
   * 修改server信息
   *
   * @param int $svid
   * @param array $aE
   * @return int
   */
  public function update( $svid, $aE ) {
    if( !$svid = uint( $svid ) ) {
      return 0;
    }
    
    $set = '';
    $aCan = array('svip', 'svport', 'svstatus', 'svmaxuser', 'svusernum', 'svtype' );
    foreach ( $aE as $k => $v ) {
      $v = model::db()->escape( $v );
      if( in_array( $k, $aCan ) ) $set .= "$k='$v',";
    }
    if( !strlen( $set ) ) {
      return 0;
    }
    $set = substr( $set, 0, -1 );
    
    $sql = "UPDATE $this->server SET $set WHERE svid='$svid' LIMIT 1";
    model::db()->exe( $sql );
    $flag = model::db()->update_rows();
    
    return $flag;
  }
}





